<template>
  <dys-modal
    :open="open"
    :title="placeholder"
    :width="width"
    @cancel="emit('cancel')"
    :footer="multiple ? undefined : false"
    @ok="handleUpdate"
  >
    <dys-search-form
      v-if="slots['search-form']"
      @search="reload"
      @reset="handleReset"
      :hide-btn-text="hideBtnText"
    >
      <slot name="search-form" :params="params"></slot>
    </dys-search-form>
    <dys-table
      :columns="columns"
      :loading="state.loading"
      :data-source="state.dataSource"
      :pagination="state.pagination"
      :row-selection="rowSelection"
      :custom-row="customRow"
      :row-key="fieldNames.value"
      @change="handleChange"
      @reload="reload"
    >
      <template v-for="name in Object.keys(slots)" #[name]="slotProps">
        <slot :name="name" v-bind="slotProps"></slot>
      </template>
    </dys-table>
  </dys-modal>
</template>
<script lang="ts" setup>
import type { PopupSelectProps } from "../typing";
import { useFetchPage } from "@/hook/useFetchPage";
import { reactive, watch } from "vue";
import { cloneDeep } from "lodash";
import { useTableSelect } from "@/hook/useTableSelect";
interface Props extends PopupSelectProps {
  /**弹窗 */
  open: boolean;
  /**控件选中keys */
  keys: string[];
  /**控件选中数据 */
  rows: any[];
  /**隐藏搜索操作按钮文本 */
  hideBtnText?: boolean;
}
const props = defineProps<Props>();
const emit = defineEmits(["cancel", "ok"]);
const slots = defineSlots();
const params = reactive(cloneDeep(props.defaultParams));
const { state, reload, handleChange } = useFetchPage(props.queryByPage, {
  autoFetch: false,
  params,
  simple: true,
});

/**多选确定 */
const handleUpdate = () => {
  emit(
    "ok",
    cloneDeep(rowSelection.selectedRowKeys),
    cloneDeep(selectedRows.value)
  );
  emit("cancel");
};

const { rowSelection, selectedRows, customRow } = useTableSelect(
  props.fieldNames.value,
  {
    multiple: props.multiple,
    onChange: handleUpdate,
  }
);

/**重置 */
const handleReset = () => {
  // 把已有参数key的值value置为null
  const reset = Object.keys(params).reduce((p, key) => {
    p[key] = null;
    return p;
  }, {});
  // 覆盖params参数
  Object.assign(params, reset, props.defaultParams);
};

watch(
  () => props.open,
  (open) => {
    if (open) {
      handleReset();
      reload();
      rowSelection.selectedRowKeys = cloneDeep(props.keys) ?? [];
      selectedRows.value = cloneDeep(props.rows) ?? [];
    }
  }
);
</script>
